<!-- 收件人-填写 -->
<template>
	<div class="dashboard-container">
		<el-form
			class="SenderWrite-container"
			ref="formRef"
			label-position="right"
			label-width="100px"
			:model="formData"
			:rules="formRules"
			@submit.prevent="handleSubmit"
		>
			<!-- 基本信息 -->
			<el-form-item :label="$t('message.senderNews.pageSenderName')" prop="name" required>
				<el-input
					style="width: 15rem"
					v-model="formData.name"
					:placeholder="$t('message.senderNews.pageSenderNameHolder')"
					clearable
					class="custom-input"
				/>
			</el-form-item>

			<el-form-item :label="$t('message.senderNews.pageSenderEmail')" prop="email" required>
				<el-input
					style="width: 15rem"
					v-model="formData.email"
					:placeholder="$t('message.senderNews.pageSenderEmailHolder')"
					clearable
					@blur="validateEmail"
					class="custom-input"
				/>
			</el-form-item>

			<!-- 操作按钮 -->
			<el-form-item class="form-actions">
				<el-button type="primary" @click="handleSubmit"> {{ $t('message.senderNews.pageSubmitForm') }} </el-button>
				<el-button @click="handleReset">{{ $t('message.senderNews.pageResetForm') }}</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { onMounted, defineComponent, reactive, ref } from 'vue';

export default defineComponent({
	name: 'SenderWrite',

	components: {},

	setup(props, { emit }) {
		const formRef = ref<FormInstance | null>(null);
		const formData = reactive({
			name: '',
			email: '',
		});

		// 邮箱验证方法
		const validateEmail = (rule: any, value: string, callback: any) => {
			if (!value) {
				return callback(new Error('请输入邮箱地址'));
			}

			// 方法2: 自定义正则验证
			const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
			if (!emailRegex.test(value)) {
				return callback(new Error('请输入有效的邮箱地址'));
			}

			callback();
		};

		const formRules = reactive<FormRules>({
			name: [
				{ required: true, message: '请输入收件人姓名', trigger: 'blur' },
				{ min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' },
			],
			email: [
				{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
				{ validator: validateEmail, trigger: ['blur', 'change'] },
			],
		});

		// 表单重置
		const handleReset = () => {
			formRef.value?.resetFields();
		};

		// 表单提交
		const handleSubmit = async () => {
			if (!formRef.value) return;

			try {
				await formRef.value.validate();
				console.log('表单验证通过，提交数据:', formData);
				// 这里添加实际提交逻辑
			} catch (error) {
				console.log('表单验证失败:', error);
			}
		};

		onMounted(() => {});

		return {
			formRef,
			formData,
			formRules,
			handleReset,
			handleSubmit,
			validateEmail,
		};
	},
});
</script>

<style lang="scss">
.SenderWrite-container {
	.el-form-item__label {
		color: #fff;
	}
}
</style>
